package swing.chapter04;

import swing.util.SwingConsle;

import javax.swing.*;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

/**
 * 表格
 */
public class JTable3 extends JFrame {

    public JTable3() {
        // 表格头
        Vector<String> columnNames = new Vector<>();
        columnNames.add("编号");
        columnNames.add("姓名");
        columnNames.add("年龄");

        // 表格数据
        Vector<Vector<String>> rowData = new Vector<>();
        for(int i=1;i<10;i++){
            Vector<String> row = new Vector<>();
            row.add(i*10+"");
            row.add(i + "张三");
            row.add(i * 8 + "");

            rowData.add(row);
        }
        JTable jTable = new JTable(rowData, columnNames);
        // 设置选择模式-多选
        jTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        add(jTable);

        // 将表格头展示到上方, JTabel 不用 JScrollPane 包裹时不显示表格头
        JTableHeader tableHeader = jTable.getTableHeader();
        add(tableHeader, BorderLayout.NORTH);

        JPanel opts = new JPanel();
        opts.setLayout(new FlowLayout());

        JButton allBtn = new JButton("全选");
        allBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jTable.selectAll();
            }
        });
        opts.add(allBtn);

        JButton backBtn = new JButton("反选");
        backBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int rowCount = jTable.getRowCount();
                int[] selectedRows = jTable.getSelectedRows();
                jTable.clearSelection();

                for(int i=0;i<rowCount;i++){
                    boolean contains = false;
                    for(int sr : selectedRows){
                        if(sr == i){
                            contains = true;
                        }
                    }

                    if(!contains){
                        jTable.addRowSelectionInterval(i, i);
                    }
                }
            }
        });
        opts.add(backBtn);

        JButton clearBtn = new JButton("取消选择");
        clearBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jTable.clearSelection();;
            }
        });
        opts.add(clearBtn);

        add(opts, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        SwingConsle.run(new JTable3(), 300, 200);
    }
}
